package com.demo.web;

import com.demo.pojo.User;
import com.demo.service.UserService;
import com.demo.service.imp.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注册");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String address = req.getParameter("address");
        String code = req.getParameter("code");
        // 从session中获取验证码数据
        resp.setContentType("text/html;charset=utf-8");
        Object serverImgCode = req.getSession().getAttribute("serverImgCode");
        // 这里需要将session中的验证码直接删除
        req.getSession().removeAttribute("serverImgCode");
        if(serverImgCode == null || code == null || !(code.equalsIgnoreCase((String) serverImgCode))){
            resp.getWriter().write("验证码错误");
            return;
        }
        // 还需要对其他的数据做非空等校验
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        user.setName(username);
        user.setSex(sex);
        user.setAddress(address);

        // 调用service层方法
        Boolean bool = this.userService.register(user);
        if( bool ){
            resp.getWriter().write("注册成功");
        }else{
            resp.getWriter().write("注册失败");
        }
    }
}
